package com.example.study.serviceImpl;

import com.example.study.event.MyEvent;
import com.example.study.mapper.UserMapper;
import com.example.study.entity.User;
import com.example.study.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.SQLException;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private ApplicationContext applicationContext;
    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    @Transactional
    public Integer insertUser(User user) {
        // 插入用户信息
        userMapper.insertUser(user);
        // 手动抛出异常
        throw new RuntimeException();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertUser3(User user) {
        try {
            // 插入用户信息
            userMapper.insertUser(user);
            // 手动抛出异常
            throw new SQLException("数据库异常");
        } catch (Exception e) {
            // 异常处理逻辑
        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized Integer insertUser4(User user) {
        // 实际中的具体业务……
        userMapper.insertUser(user);
        return 1;
    }
    /**
     * 获取用户信息
     * @return
     */
    public User getUser() {
        // 实际中会根据具体的业务场景，从数据库中查询对应的信息
        return new User(4, "张三1", "111111");
    }
    /**
     * 发布事件
     * @return
     */
    public User getUser2() {
        User user = new User(4, "张三1", "111111");
        // 发布事件
        MyEvent event = new MyEvent(this, user);
        applicationContext.publishEvent(event);
        return user;
    }
}